package models

import (
	"log"
	"fmt"
)

type Data struct {
	Id int
	CreatedAt int
	Name string
	Sorting int
	Status int
}

// 查询数据
func SelectDatas(sql string, args ...interface{}) (datas []Data, err error) {
	rows, err := DB.Raw(sql, args...).Rows()
	if err != nil {
		panic(err)
		//return
    }
	for rows.Next() {
		conv := Data{}
        if err = rows.Scan(&conv.Id, &conv.Name, &conv.CreatedAt); err != nil {
			//return
			panic(err)
		}
        datas = append(datas, conv)
	}
	rows.Close()
	return
}

// 统计数据
func CountDatas(sql string, args ...interface{}) (count int) {
	rows, _ := DB.Raw(sql, args...).Rows()
	for rows.Next() {
        rows.Scan(&count)
    }
	return
}

// 统计金额
func SumDatasAmount(sql string, args ...interface{}) (amount float32) {
	rows, _ := DB.Raw(sql, args...).Rows()
	for rows.Next() {
        rows.Scan(&amount)
    }
    return
}

//	Insert 插入操作
func Insert(sql string, args... interface{}) (int64, error) {
	result := DB.Exec(sql, args...)
	id := result.RowsAffected
	fmt.Printf("新增成功，新增ID为%d\n", id)
	return id, nil
}

//	Update 修改操作
func Update(sql string, args... interface{}) (valid bool, err error) {
	result := DB.Exec(sql, args...)
	num := result.RowsAffected
	fmt.Printf("修改成功，修改行数为%d\n", num)
	valid = true
    return
}

//	Delete 删除操作
func Delete(sql string, args... interface{}) (valid bool, err error) {
	result := DB.Exec(sql, args...)
    num := result.RowsAffected
	fmt.Printf("删除成功，删除行数为%d\n", num)
	valid = true
    return
}
/*
func Transaction(sql string, args... interface{}) {
    // 开启事务
    tx, err := DB.Begin()

    if err != nil {
        panic(err)
    }

    result, err := tx.Exec(sql, args...)
    if err != nil {
        // 失败回滚
        tx.Rollback()
        panic(err)
    }

    fmt.Println("result", result)

    // 提交事务
    err = tx.Commit()

    if err != nil {
        // 失败回滚
        tx.Rollback()
        panic(err)
    }
}
*/
// CheckErr 用来校验error对象是否为空
func CheckErr(err error, msg string) {
	if nil != err {
		log.Panicln(msg, err)
	}
}
